



#include <stdio.h>
#include "usart.h"

#include "serial.h"
#include "main.h"



unsigned char Uart1_Rxbuf[UART1_RXBUFLEN];    // 接收缓冲区

unsigned char Uart1_Txlen[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};      	// 当前接收长度

unsigned short int Uart1_Rxlen = 0;      // 当前发送长度
unsigned short int Uart1_Rxdlen = 0;
unsigned short int Uart1_Rxdly = 0;      // 当前接收超时
unsigned short int Uart1_Txdly = 0;      // 当前发送超时

static struct SerialTx* Head_SerialTx = NULL;
SerialTx_t SerialTx[16];

void SerialTx_Init(void)
{ 
   unsigned char  i;
   for(i=0;i<15;i++)
   {
     SerialTx[i].pTxBuf = NULL;
     SerialTx[i].TxBufCnt = 0;
     SerialTx[i].Next = &SerialTx[i+1];
   }
   
   SerialTx[15].Next = &SerialTx[0];
   
   Head_SerialTx = &SerialTx[0];
}

void SerialTx_InsertBuff(unsigned char *buf,unsigned char len)
{
	unsigned char i;
  
  struct SerialTx *pSerialTx = Head_SerialTx;
  
  if(len >  UART1_TXBUFLEN)
    len = UART1_TXBUFLEN;
  
  while(pSerialTx->pTxBuf != NULL)
  {
    pSerialTx = pSerialTx->Next;
    if(pSerialTx == Head_SerialTx)    //找到第一个
    {
      return;   // 满了,不插入数据了.
    }  
  }
  pSerialTx->pTxBuf = pSerialTx->TxBuf;
  pSerialTx->TxBufCnt = len;
  
  for(i=0;i<len;i++)
  {
      pSerialTx->pTxBuf[i] = buf[i];
  }
}
void SerialTx_ReStarTx(void)
{
  struct SerialTx *pSerialTx = Head_SerialTx;
  {
    if(pSerialTx->pTxBuf != NULL)
      HAL_UART_Transmit_IT(&huart1,pSerialTx->pTxBuf,pSerialTx->TxBufCnt);    //发送当前
  }
}
// 发送完成
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
  struct SerialTx *pSerialTx = Head_SerialTx;

  if(huart->Instance == USART1)
  {
    if(pSerialTx != NULL)
    {
      pSerialTx->pTxBuf = NULL;
      pSerialTx->TxBufCnt = 0;
      pSerialTx = pSerialTx->Next;
      Head_SerialTx = pSerialTx;      // 指向下一个需要发送的缓冲区
    }
  }
}


